﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace DDD.Api.StartupExtensions
{
    public class LongContractResolver : CamelCasePropertyNamesContractResolver
    {
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {
            if (objectType == typeof(long))
            {
                return new JsonConverterLong();
            }

            return base.ResolveContractConverter(objectType);
        }
    }

    public class JsonConverterLong : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        private static string GetDefaultLongStr(object? objValue)
        {
            if (objValue == null)
            {
                return "0";
            }

            string text = objValue!.ToString();
            if (string.IsNullOrWhiteSpace(text))
            {
                return "0";
            }

            return text;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if ((reader.ValueType == null || reader.ValueType == typeof(long?)) && reader.Value == null)
            {
                return 0;
            }

            long.TryParse(GetDefaultLongStr(reader.Value), out var result);
            return result;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteValue(value);
            }
            else
            {
                writer.WriteValue(value.ToString());
            }
        }
    }
}

